package com.jinly.ryder.flow.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jinly.ryder.flow.dao.FlowRuleMapper;
import com.jinly.ryder.flow.dao.FlowStepMapper;
import com.jinly.ryder.flow.dao.entity.FlowRuleDO;
import com.jinly.ryder.flow.dao.entity.FlowStepDO;
import com.jinly.ryder.flow.service.FlowRuleService;
import com.jinly.ryder.flow.service.mapping.FlowRuleMapping;
import com.jinly.ryder.flow.service.mapping.FlowStepMapping;
import com.jinly.ryder.flow.service.model.FlowRule;
import com.jinly.ryder.flow.service.model.FlowStep;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class FlowRuleServiceImpl implements FlowRuleService {

    private final FlowRuleMapper flowRuleMapper;
    private final FlowStepMapper flowStepMapper;
    private final FlowRuleMapping flowRuleMapping;
    private final FlowStepMapping flowStepMapping;

    @Override
    public FlowRule getRule(Integer flowRuleId) {
        FlowRule flowRule = flowRuleMapping.toModel(flowRuleMapper.selectById(flowRuleId));
        if (flowRule != null) {
            flowRule.setStepList(queryFlowStepList(flowRule.getId()));
        }
        return flowRule;
    }

    @Override
    public List<FlowRule> flowRuleList() {
        Wrapper<FlowRuleDO> queryWrapper = new QueryWrapper<FlowRuleDO>().lambda()
                .eq(FlowRuleDO::getActive, true)
                .orderByDesc(FlowRuleDO::getId);
        return flowRuleMapping.toModelList(flowRuleMapper.selectList(queryWrapper));
    }


    @Override
    public FlowRule getRuleByName(String flowName) {
        Wrapper<FlowRuleDO> queryWrapper = new QueryWrapper<FlowRuleDO>().lambda()
                .eq(FlowRuleDO::getName, flowName)
                .eq(FlowRuleDO::getActive, true)
                .orderByDesc(FlowRuleDO::getId)
                .last("limit 1");
        FlowRule flowRule = flowRuleMapping.toModel(flowRuleMapper.selectOne(queryWrapper));
        if (flowRule != null) {
            flowRule.setStepList(queryFlowStepList(flowRule.getId()));
        }
        return flowRule;
    }


    private List<FlowStep> queryFlowStepList(Integer flowRuleId) {
        Wrapper<FlowStepDO> queryWrapper = new QueryWrapper<FlowStepDO>().lambda()
                .eq(FlowStepDO::getFlowRuleId, flowRuleId);
        return flowStepMapping.toModelList(flowStepMapper.selectList(queryWrapper));
    }
}
